"""
SHTC3 temperature and humidity sensor driver.
The SHTC3 is a digital humidity and temperature sensor designed especially for battery-driven high-volume consumer electronics applications.
"""

import utime
from usr.libs.i2c import I2CIOWrapper


SHTC3_SLAVE_ADDR = 0x70

# Commands
SHTC3_WAKEUP            =   b"\x3517"
SHTC3_SLEEP		        =	b"\xB098"
SHTC3_NM_CE_READ_TH     =	b"\x7CA2"
SHTC3_NM_CE_READ_RH     =	b"\x5C24"
SHTC3_NM_CD_READ_TH     =	b"\x7866"
SHTC3_NM_CD_READ_RH     =	b"\x58E0"
SHTC3_LM_CE_READ_TH     =	b"\x6458"
SHTC3_LM_CE_READ_RH     =	b"\x44DE"
SHTC3_LM_CD_READ_TH     =	b"\x609C"
SHTC3_LM_CD_READ_RH     =	b"\x401A"
SHTC3_SOFTWARE_RESET    =	b"\x401A"
SHTC3_ID                = 	b"\xEFC8"


class Shtc3(I2CIOWrapper):

    def wakeup(self):
        self.write(SHTC3_WAKEUP, b'')
        utime.sleep_ms(30)

    def sleep(self):
        self.write(SHTC3_SLEEP, b'')

    def soft_reset(self):
        self.write(SHTC3_SOFTWARE_RESET)
        utime.sleep_ms(30)

    @staticmethod
    def checkCrc(data, checksum):
        crc = 0xFF
        for d in data:
            crc ^= d
            for _ in range(8):
                if(crc & 0x80):
                    crc = (crc << 1) ^ 0x31
                else:
                    crc = crc << 1
        return crc == checksum

    def __getValue(self):
        utime.sleep_ms(20)
        data = self.read(b'', 3)
        if self.checkCrc(data[:2], 2, data[2]):
            return data[0] << 8 | data[1]

    def getTempValue(self):
        """Calculate the temperature value."""
        self.write(SHTC3_NM_CD_READ_RH, b'')
        value = self.__getValue()
        value = 175 * value / 65536.0 - 45.0
        return value

    def getHumiValue(self):
        """Calculate the humidity value."""
        self.write(SHTC3_NM_CD_READ_RH, b'')
        value = self.__getValue()
        value = 100 * value / 65536.0
        return value


if __name__ == "__main__":
    from machine import I2C

    sht30_dev = Shtc3(I2C(I2C.I2C0, I2C.FAST_MODE), SHTC3_SLAVE_ADDR)
    for i in range(10):
        sht30_dev.wakeup()
        temp = sht30_dev.getTempValue()
        humi = sht30_dev.getHumiValue()
        sht30_dev.sleep()
        print("Temperature = {:.2f}°C , Humidity = {:.2f} %\n".format(temp, humi))
